package com.spark.common.helper

import android.content.Context
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.spark.common.R

object BottomSheet {
    fun show(context: Context, items: MutableList<String>, listener: (BaseQuickAdapter<Any,BaseViewHolder>,View,Int)->Unit?) {
        val bottomSheetDialog = BottomSheetDialog(context)
        val rootView = LayoutInflater.from(context).inflate(R.layout.bottom_dialog_layout, null)
        val recyBottomCategory = rootView.findViewById<RecyclerView>(R.id.recy_bottom_category)
        val tvBottomCancel = rootView.findViewById<TextView>(R.id.tv_bottom_cancel)

        val bottomItemsAdapter = BottomItemsAdapter(R.layout.item_picker)
        bottomItemsAdapter.addData(items)
        recyBottomCategory.adapter = bottomItemsAdapter
        val layoutManager = LinearLayoutManager(context)
        recyBottomCategory.layoutManager = layoutManager


        tvBottomCancel.setOnClickListener { v ->
            if (bottomSheetDialog.isShowing) {
                bottomSheetDialog.dismiss()
            }
        }

        bottomItemsAdapter.setOnItemClickListener { adapter, view, position ->
            if (bottomSheetDialog.isShowing) {
                bottomSheetDialog.dismiss()
            }
            listener(adapter,view,position)
        }


        bottomSheetDialog.setContentView(rootView)
        bottomSheetDialog.setCanceledOnTouchOutside(true)
        bottomSheetDialog.setCancelable(true)
        bottomSheetDialog.show()

    }

    /**
     * adapter
     */
    private class BottomItemsAdapter(layoutResId: Int) : BaseQuickAdapter<String, BaseViewHolder>(layoutResId) {

        override fun convert(helper: BaseViewHolder, item: String) {
            helper.setText(R.id.tv_item, item)
            if (helper.layoutPosition == data.size - 1) {
                helper.setGone(R.id.divider, false)
            }
        }
    }
}
